package com.scitc.pleasurevideo;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.scitc.pleasurevideo.adapter.HistorySearchAdapter;
import com.scitc.pleasurevideo.adapter.MenuTvContentAdapter;
import com.scitc.pleasurevideo.base.ETActivity;
import com.scitc.pleasurevideo.data.HistoryDataMan;
import com.scitc.pleasurevideo.helper.ForwardHelper;
import com.scitc.pleasurevideo.pojo.DoubanTvVo;
import com.scitc.pleasurevideo.pojo.MenuTvVo;
import com.scitc.pleasurevideo.pojo.VideoSourceVo;
import com.scitc.pleasurevideo.util.AtyContainer;
import com.scitc.pleasurevideo.util.MenuUrlUtil;
import com.scitc.pleasurevideo.view.SwDialog;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author contradiction
 */
public class SearchActivity extends ETActivity {

    private RelativeLayout queryBtn;
    private EditText queryText;
    private ImageView igClearHistory;
    private ListView historyList;
    private HistorySearchAdapter madapter;
    private List<String> historyItems = new ArrayList<>();
    private RelativeLayout rlHistory;
    private RelativeLayout rlSearch;
    private TextView searchText;
    private ListView mListView;
    private MenuTvContentAdapter mAdapter;
    private List<MenuTvVo> searchItems = new ArrayList<MenuTvVo>();
    private int searchItemsNum = 0;
    private ImageView igDeleteSearch;
    private RelativeLayout nullSearchItem;

    private Timer timer = new Timer();
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            if (msg.what == 1) {
                nullSearchItem.setVisibility(View.GONE);
            }
        }
    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        initView();
        onClick();
        loadHistorywords();
    }

    /**
     * 加载历史搜索记录
     */
    public void loadHistorywords() {
        List<String> items = HistoryDataMan.getHistoryDataMan().getHistoryQueryKeywords(mInstance);
        if (items.size() < 1) {
            igClearHistory.setVisibility(View.GONE);
        } else {
            igClearHistory.setVisibility(View.VISIBLE);
            madapter.addAll(items);
        }
    }

    /**
     * 显示历史搜索记录列表
     */
    private void sethistorylistvisityvisible() {
        rlSearch.setVisibility(View.GONE);
        rlHistory.setVisibility(View.VISIBLE);
    }

    /**
     * 隐藏历史搜索记录列表
     */
    private void sethistorylistvisitygone() {
        rlHistory.setVisibility(View.GONE);
        rlSearch.setVisibility(View.VISIBLE);
        nullSearchItem.setVisibility(View.GONE);
    }

    /**
     * 点击了搜索按钮
     */
    private void queryBtnClick() {
        mAdapter.clearItem();
        searchItemsNum = 0;
        searchText.setText("已搜索到" + searchItemsNum + "个资源");
        judgeSearchText();
    }

    /**
     * 点击事件
     */
    private void onClick() {
        //查询按钮的点击事件
        queryBtn.setOnClickListener(view -> queryBtnClick());
        //清除搜索文字
        igDeleteSearch.setOnClickListener(view -> {
            queryText.setText("");
            sethistorylistvisityvisible();
            searchItemsNum = 0;
            mAdapter.clearItem();
        });
        //在搜索框内判断输入的文字长度
        queryText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (TextUtils.isEmpty(queryText.getText()) || queryText.getText().toString().trim().length() < 1) {
                    sethistorylistvisityvisible();
                    searchItemsNum = 0;
                    igDeleteSearch.setVisibility(View.GONE);
                } else {
                    igDeleteSearch.setVisibility(View.VISIBLE);
                }
            }
        });
        //搜索结果列表点击item
        mListView.setOnItemClickListener((adapterView, view, i, l) -> {
            MenuTvVo menuTvPojo = mAdapter.getItem(i);
            DoubanTvVo doubanTvPojo = new DoubanTvVo();
            assert menuTvPojo != null;
            doubanTvPojo.setTitle(menuTvPojo.getName());
            ForwardHelper.toTvPlayMenuActivity(mInstance, doubanTvPojo, menuTvPojo);
        });
        //清除历史搜索记录
        igClearHistory.setOnClickListener(view -> {
            SwDialog swDialog=new SwDialog(mInstance,"全部删除","是否删除全部搜索历史？");
            swDialog.setOkListener(() -> HistoryDataMan.getHistoryDataMan().clearHistoryQueryKeyword(mInstance));
            swDialog.show();
        });
        //历史记录列表的item点击事件
        historyList.setOnItemClickListener((adapterView, view, i, l) -> {
            String name = madapter.getItem(i);
            queryText.setText(name);
            queryBtnClick();
        });
        //在搜素框内点击软键盘回车按钮
        queryText.setOnKeyListener((v, keyCode, event) -> {
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_UP) {
                queryBtnClick();
            }
            return false;
        });
    }

    /**
     * 是否跳转搜索的界面
     */
    private void judgeSearchText() {
        hideInput();
        if (TextUtils.isEmpty(queryText.getText()) || queryText.getText().toString().trim().length() < 1) {
            Toast.makeText(mInstance, "请输入要搜索的名字", Toast.LENGTH_SHORT).show();
            sethistorylistvisityvisible();
        } else {
            sethistorylistvisitygone();
            loadSearchData(queryText.getText().toString().trim());
            HistoryDataMan.getHistoryDataMan().addHistoryQueryKeyword(mInstance, queryText.getText().toString().trim());
            madapter.addItem(queryText.getText().toString().trim());
        }
    }

    /**
     * 加载搜索到的网络数据
     */
    private void loadSearchData(final String name) {
        final List<VideoSourceVo> urlApiPojoList = MenuUrlUtil.getUrlApiList();
        if(urlApiPojoList==null||urlApiPojoList.size()<1){
            Toast.makeText(mInstance, "没有视频资源列表，请到设置界面，更新影视源", Toast.LENGTH_SHORT).show();
            return;
        }
        //子线程开始搜索
        runOnUiThread(() -> {
            for (VideoSourceVo urlApiPojo : urlApiPojoList) {
                if (TextUtils.isEmpty(queryText.getText()) || queryText.getText().toString().trim().length() < 1) {
                    break;
                }
                MenuUrlUtil.getMenuUrlOkgo(mInstance, urlApiPojo.getSource_url_html_str(), urlApiPojo.getSource_url_search_str(), name);
            }
        });
        //子线程开始搜索成功后的一个回调
        MenuUrlUtil.setMenuTvListListenr(new MenuUrlUtil.MenuTvListListenr() {
            @SuppressLint("SetTextI18n")
            @Override
            public void menuTvListListenr(List<MenuTvVo> menuTvPojoList) {
                //判断搜索框的文字长度
                if (TextUtils.isEmpty(queryText.getText()) || queryText.getText().toString().trim().length() < 1) {
                    rlSearch.setVisibility(View.GONE);
                    rlHistory.setVisibility(View.VISIBLE);
                    searchItemsNum = 0;
                    return;
                }

                //判断返回的列表是否为空
                if(menuTvPojoList==null||menuTvPojoList.size()<1){
                    return;
                }

                //去除返回的列表里面没有包含搜索名字的列表
                //去除与搜索文字不匹配的item
                for (int i = 0; i < menuTvPojoList.size(); i++) {
                    if (!menuTvPojoList.get(i).getName().contains(name)) {
                        menuTvPojoList.remove(i);
                        i--;
                    }
                }
                //判断在移除不匹配的资源后还有没有数据
                if (menuTvPojoList.size() < 1) {
                    if (searchItemsNum < 1) {
                        sethistorylistvisityvisible();
                        nullSearchItem.setVisibility(View.VISIBLE);
                        setTimer();
                    } else {
                        sethistorylistvisitygone();
                    }
                    return;
                }
                mAdapter.addItems(menuTvPojoList);
                searchItemsNum += menuTvPojoList.size();
                searchText.setText("已搜索到" + searchItemsNum + "个资源");
            }

            @Override
            public void menuTvIntroduction(String introduction) {

            }
        });
    }

    /**
     * 初始化控件
     */
    private void initView() {
        queryBtn = (RelativeLayout) findViewById(R.id.queryBtn);
        queryText = (EditText) findViewById(R.id.queryText);
        igClearHistory = (ImageView) findViewById(R.id.igClearHistory);
        historyList = (ListView) findViewById(R.id.historyList);
        madapter = new HistorySearchAdapter(mInstance, historyItems);
        historyList.setAdapter(madapter);
        rlHistory = (RelativeLayout) findViewById(R.id.rl_history);
        rlSearch = (RelativeLayout) findViewById(R.id.rl_search);
        searchText = (TextView) findViewById(R.id.search_text);
        mListView = (ListView) findViewById(R.id.xListView);
        nullSearchItem = (RelativeLayout) findViewById(R.id.nullSearchItem);

        mAdapter = new MenuTvContentAdapter(this, searchItems);
        mListView.setAdapter(mAdapter);
        igDeleteSearch = (ImageView) findViewById(R.id.ig_delete_search);
    }

    private void setTimer() {
        timer.cancel();
        timer = null;
        timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 1;
                handler.sendMessage(message);
            }
        }, 1000, 1);
    }

    @Override
    public void finish() {
        super.finish();
    }


    /**
     * 显示键盘
     *
     * @param et 输入焦点
     */
    public void showInput(final EditText et) {
        et.requestFocus();
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        imm.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT);
    }

    /**
     * 隐藏键盘
     */
    protected void hideInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        View v = getWindow().peekDecorView();
        if (null != v) {
            imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
        }
    }
}
